package pool.book;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * @Author Administrator
 * @Date 2020/5/26 16:20
 **/
public class BookDaoDB implements BookDao{
    JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());

    String sql="";
    @Override
    public int insert(Book book) {
        /*用户名不能重复：
            判断是否重复，selectByName返回值为空就不重复

            准备sql语句，用JdbcTemplate执行sql语句
        * */
        Book b=selectByName(book.getName());
        if (b==null){
            sql="insert into book(name,press,author,price) values(?,?,?,?)";
            int i=template.update(sql,
                    book.getName(),book.getPress(),
                    book.getAuthor(),book.getPrice());
            return i;
        }else{
            return -1;
        }



    }

    @Override
    public List<Book> selectAll() {
        sql="select * from book";
        try {
            return template.query(sql,new BeanPropertyRowMapper<Book>(Book.class));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int update(int id, Book book) {
        sql="update book set name=?,press=?,author=?,price=?";
        int i=template.update(sql,book.getName(),book.getPress(),book.getAuthor(),book.getPrice());

        return i;
    }

    @Override
    public int delete(int id) {
        sql="delete from book where id=?";
        return template.update(sql,id);
    }

    @Override
    public Book selectByName(String name) {
        /*
        * 对于查询语句，使用template的
        * 1.queryForObject()基本上返回结果是单条记录或者没有
        * 2.query()返回多条记录（集合List）或者null
        * 方法需要三个参数：
        * sql:select语句        *
        * new BeanPropertyRowMapper<>()：查询出的记录自动封装成Book对象
        * 给？占位符的赋值，取决于问号数量*/

        sql ="select * from book where name=?";
        Book book= template.queryForObject(sql,new BeanPropertyRowMapper<Book>(Book.class),name);
        return book;
    }
}
